package com.cskaoyan.service;

import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.CheckoutVo;
import com.cskaoyan.domain.*;
import com.cskaoyan.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketAddressMapper addressMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;
    @Autowired
    MarketSystemMapper systemMapper;
    public Integer getGoodsCountByUserId(Integer userId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId);
        List<MarketCart> cartList = cartMapper.selectByExampleSelective(cartExample);
        Integer data=cartList.size();
        return data;
    }
    @Override
    @Transactional
    public BaseRespVo addCartGoods(Integer goodsId, Integer userId, Integer number, Integer productId) {
        MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
        if (goods == null) {
            return BaseRespVo.badArgument();
        }
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andGoodsIdEqualTo(goodsId).andProductIdEqualTo(productId);
        // List<MarketCart> userCarts = cartMapper.selectByExampleSelective(cartExample);
        //cartExample.createCriteria().andGoodsIdEqualTo(goodsId).andProductIdEqualTo(productId);
        // cartExample.createCriteria().andGoodsIdEqualTo(goodsId).andUserIdEqualTo(userId);
        //该用户买的商品的cart信息，只有一个
        List<MarketCart> cartList = cartMapper.selectByExampleSelective(cartExample);
        MarketCartExample userCartExample = new MarketCartExample();
        userCartExample.createCriteria().andUserIdEqualTo(userId);
        //该用户加入购物车的所有商品
        List<MarketCart> userCarts = cartMapper.selectByExampleSelective(userCartExample);
        Integer data=userCarts.size();

        if (cartList.size() != 0) {
            Short preNumber = cartList.get(0).getNumber();
            cartList.get(0).setNumber((short) (preNumber+number));
            cartList.get(0).setUpdateTime(LocalDateTime.now());
            MarketGoodsProductExample productExample = new MarketGoodsProductExample();
            productExample.createCriteria().andSpecificationsEqualTo(cartList.get(0).getSpecifications()).andIdEqualTo(productId);
            List<MarketGoodsProduct> productList = productMapper.selectByExampleSelective(productExample);
            Integer stocks = productList.get(0).getNumber();
            if (number > stocks) {
                return BaseRespVo.fail("库存不足！");
            }
            cartMapper.updateByExampleSelective(cartList.get(0),cartExample);
        }
        else {

            MarketCart cart = new MarketCart();
            cart.setUserId(userId);
            cart.setGoodsId(goodsId);
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setGoodsName(goods.getName());
            //要查product表获取productid
            cart.setProductId(productId);
            cart.setPrice(goods.getRetailPrice());
            cart.setNumber(Short.valueOf(number.toString()));
            //查product表获得specifications
            MarketGoodsProduct product = productMapper.selectByPrimaryKey(productId);
            cart.setSpecifications(product.getSpecifications());
            MarketGoodsProductExample productExample = new MarketGoodsProductExample();
            productExample.createCriteria().andSpecificationsEqualTo(product.getSpecifications()).andIdEqualTo(productId);
            List<MarketGoodsProduct> productList = productMapper.selectByExampleSelective(productExample);
            Integer stocks = productList.get(0).getNumber();
            if (number > stocks) {
                return BaseRespVo.fail("库存不足！");
            }
            cart.setChecked(false);
            cart.setPicUrl(goods.getPicUrl());
            cart.setAddTime(LocalDateTime.now());
            cart.setUpdateTime(LocalDateTime.now());
            cart.setDeleted(false);
            cartMapper.insertSelective(cart);

        }
        data+=number;
        return BaseRespVo.ok(data);
    }

    @Override
    public BaseRespVo selectCartIndexByUserId(Integer userId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<MarketCart> cartList = cartMapper.selectByExampleSelective(cartExample);
        Map<String,Object> cartTotal=new HashMap<>();
        Integer checkedGoodsCount=0;
        Integer goodsCount=0;
        BigDecimal checkedGoodsAmount=BigDecimal.ZERO;
        BigDecimal goodsAmount=BigDecimal.ZERO;
        for (MarketCart marketCart : cartList) {
            Boolean cartChecked = marketCart.getChecked();
            Short cartNumber = marketCart.getNumber();
            BigDecimal cartPrice = marketCart.getPrice();
            if (cartChecked) {
                checkedGoodsCount += Integer.parseInt(cartNumber.toString());
                goodsCount+=cartNumber;
                BigDecimal multiply = cartPrice.multiply(new BigDecimal(cartNumber.toString()));
                BigDecimal add = checkedGoodsAmount.add(multiply);
                checkedGoodsAmount=add;
                BigDecimal addgoods = goodsAmount.add(multiply);
                goodsAmount=addgoods;

            } else {
                goodsCount+=cartNumber;
                BigDecimal multiply = cartPrice.multiply(new BigDecimal(cartNumber.toString()));
                BigDecimal addgoods = goodsAmount.add(multiply);
                goodsAmount=addgoods;
            }
        }
        cartTotal.put("checkedGoodsCount",checkedGoodsCount);
        cartTotal.put("goodsCount",goodsCount);
        cartTotal.put("checkedGoodsAmount",checkedGoodsAmount);
        cartTotal.put("goodsAmount",goodsAmount);
        Map<String,Object> data=new HashMap<>();
        data.put("cartList",cartList);
        data.put("cartTotal",cartTotal);
        return BaseRespVo.ok(data);
    }

    @Override
    public BaseRespVo checkCart(Integer isChecked, List<Integer> productIds, Integer userId) {
        for (Integer productId : productIds) {
            MarketCartExample cartExample = new MarketCartExample();
            cartExample.createCriteria().andProductIdEqualTo(productId);
            List<MarketCart> cartList = cartMapper.selectByExampleSelective(cartExample);
            if (isChecked == 1) {
                cartList.get(0).setChecked(true);
            } else {
                cartList.get(0).setChecked(false);
            }
            cartMapper.updateByExampleSelective(cartList.get(0),cartExample);
        }

        BaseRespVo baseRespVo = this.selectCartIndexByUserId(userId);
        return baseRespVo;
    }

    @Override
    public BaseRespVo fastAddCartGoods(Integer goodsId, Integer userId, Integer number, Integer productId) {
        Integer data=null;
        MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
        if (goods == null) {
            return BaseRespVo.badArgument();
        }
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andGoodsIdEqualTo(goodsId).andProductIdEqualTo(productId);
        //该用户买的商品的cart信息，只有一个
        List<MarketCart> cartList = cartMapper.selectByExampleSelective(cartExample);
       /* MarketCartExample userCartExample = new MarketCartExample();
        userCartExample.createCriteria().andUserIdEqualTo(userId);*/
        //如果购物车内有该商品记录，做一个覆盖
        if (cartList.size() != 0) {
            cartList.get(0).setNumber(Short.valueOf(number.toString()));
            cartList.get(0).setUpdateTime(LocalDateTime.now());
            MarketGoodsProductExample productExample = new MarketGoodsProductExample();
            productExample.createCriteria().andSpecificationsEqualTo(cartList.get(0).getSpecifications()).andIdEqualTo(productId);
            List<MarketGoodsProduct> productList = productMapper.selectByExampleSelective(productExample);
            Integer stocks = productList.get(0).getNumber();
            if (number > stocks) {
                return BaseRespVo.fail("库存不足！");
            }
            cartMapper.updateByExampleSelective(cartList.get(0), cartExample);
            data=cartList.get(0).getId();
        } else {
            MarketCart cart = new MarketCart();
            cart.setUserId(userId);
            cart.setGoodsId(goodsId);
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setGoodsName(goods.getName());
            //要查product表获取productid
            cart.setProductId(productId);
            cart.setPrice(goods.getRetailPrice());
            cart.setNumber(Short.valueOf(number.toString()));
            //查product表获得specifications
            MarketGoodsProduct product = productMapper.selectByPrimaryKey(productId);
            cart.setSpecifications(product.getSpecifications());
            MarketGoodsProductExample productExample = new MarketGoodsProductExample();
            productExample.createCriteria().andSpecificationsEqualTo(product.getSpecifications()).andIdEqualTo(productId);
            List<MarketGoodsProduct> productList = productMapper.selectByExampleSelective(productExample);
            Integer stocks = productList.get(0).getNumber();
            if (number > stocks) {
                return BaseRespVo.fail("库存不足！");
            }
            cart.setChecked(false);
            cart.setPicUrl(goods.getPicUrl());
            cart.setAddTime(LocalDateTime.now());
            cart.setUpdateTime(LocalDateTime.now());
            cart.setDeleted(false);
            cartMapper.insertSelective(cart);
            data=cart.getId();
        }
        return BaseRespVo.ok(data);
    }

    @Override
    public BaseRespVo getCartCheckout(CheckoutVo checkoutVo, Integer userId) {
        Integer cartId = checkoutVo.getCartId();
        Integer addressId = checkoutVo.getAddressId();
        Integer couponId = checkoutVo.getCouponId();
        Integer grouponRulesId = checkoutVo.getGrouponRulesId();
        Integer userCouponId = checkoutVo.getUserCouponId();
        List<MarketCart> checkedGoodsList=null;
        //cartId=0表示是立即购买，大于0表示是在购物车中下的单，找出要结算的cartList
        if (cartId == 0) {
            MarketCartExample cartExample = new MarketCartExample();
            cartExample.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
            checkedGoodsList = cartMapper.selectByExampleSelective(cartExample);
        } else {
            MarketCartExample cartExample = new MarketCartExample();
            cartExample.createCriteria().andUserIdEqualTo(userId).andIdEqualTo(cartId).andDeletedEqualTo(false);
            checkedGoodsList= cartMapper.selectByExampleSelective(cartExample);
        }
        //addressId=0说明没设置当前地址，自动去找默认地址，大于0去找当前地址，找到地址的list，第一个元素就是想要的地址
        List<MarketAddress> addressList=null;
        if (addressId == 0) {
            MarketAddressExample addressExample = new MarketAddressExample();
            addressExample.createCriteria().andUserIdEqualTo(userId).andIsDefaultEqualTo(true);
            addressList = addressMapper.selectByExampleSelective(addressExample);
        } else {
            MarketAddressExample addressExample = new MarketAddressExample();
            addressExample.createCriteria().andUserIdEqualTo(userId).andIdEqualTo(addressId);
            addressList=addressMapper.selectByExampleSelective(addressExample);
        }
        //可用的优惠券数量（条件多，难判断，都写完回头check一下条件判断）
        //couponId=-1说明没有优惠券id限制，去找符合条件的优惠券，大于-1就去找当前id的优惠券，注意优惠券添加不合并
        Integer availableCouponLength=0;
        MarketCoupon coupon=null;
        if (couponId == -1) {
            MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
            //userId,status=0即未使用，未被删除
            couponUserExample.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo((short) 0).andDeletedEqualTo(false);
            List<MarketCouponUser> couponUsers = couponUserMapper.selectByExampleSelective(couponUserExample);
            if (couponUsers.size() == 0) {
                availableCouponLength=0;
            } else {
                for (MarketCouponUser couponUser : couponUsers) {
                    //根据couponId，去coupon表找优惠券
                    Integer userCouponId1 = couponUser.getCouponId();
                    coupon = couponMapper.selectByPrimaryKey(userCouponId1);
                    Integer total = coupon.getTotal();
                    //total=0说明优惠券没库存了
                    if (total == 0) {
                        continue;
                    }
                    //结账总金额逻辑最后判断
                    //coupon.getMin()
                    availableCouponLength += 1;

                }
                //没选coupon就设为null
                coupon=null;
            }
        }
        else {
            coupon = couponMapper.selectByPrimaryKey(couponId);
            availableCouponLength=1;
        }




        //根据checked=1算总金额，金额超过运费满减，则不添加运费；不够满减标准，则添加运费，如果有优惠券，减去优惠券金额
        //实付金额
        BigDecimal actualPrice=BigDecimal.ZERO;
        //商品合计
        BigDecimal totalPrice=BigDecimal.ZERO;
        //运费金额
        BigDecimal freightPrice=BigDecimal.ZERO;
        //优惠劵金额
        BigDecimal couponPrice=BigDecimal.ZERO;
        for (MarketCart marketCart : checkedGoodsList) {
            BigDecimal singlePrice = marketCart.getPrice();
            Short number = marketCart.getNumber();
            totalPrice =totalPrice.add(singlePrice.multiply(new BigDecimal(number.toString()))) ;
        }
        //从system表中找freight-value和freight-min，即运费金额和满减金额
        String freightMin = systemMapper.selectKeyNameAndKeyValue("market_express_freight_min");
        String freightValue = systemMapper.selectKeyNameAndKeyValue("market_express_freight_value");
        //如果商品金额小于满减金额，则不减运费
        if (totalPrice.compareTo(new BigDecimal(freightMin)) == -1) {
            freightPrice = new BigDecimal(freightValue);
        } else {
            freightPrice=BigDecimal.ZERO;
        }
        if (coupon != null) {
            couponPrice=coupon.getDiscount();
        }
        BigDecimal orderTotalPrice = totalPrice.add(freightPrice);
        actualPrice=orderTotalPrice.subtract(couponPrice);
        Map<String,Object> data=new HashMap<>();
        data.put("actualPrice",actualPrice);
        data.put("addressId",addressList.get(0).getId());
        data.put("availableCouponLength",availableCouponLength);
        data.put("cartId",cartId);
        MarketAddress checkedAddress = addressList.get(0);
        data.put("checkedAddress",checkedAddress);
        data.put("checkedGoodsList",checkedGoodsList);
        data.put("couponId",couponId);
        data.put("couponPrice",couponPrice);
        data.put("freightPrice",freightPrice);
        data.put("goodsTotalPrice",totalPrice);
        data.put("grouponPrice",BigDecimal.ZERO);
        data.put("grouponRulesId",grouponRulesId);
        data.put("orderTotalPrice",orderTotalPrice);
        data.put("userCouponId",userCouponId);
        return BaseRespVo.ok(data);

    }

    @Override
    public int updatechecked(MarketCart goodsByProductIdAndchecked, Integer integer) {
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andProductIdEqualTo(integer);
        int i = cartMapper.updateByExample(goodsByProductIdAndchecked, marketCartExample);
        return i;
    }

    @Override
    public int updateDeleted(MarketCart marketCart, Integer productId) {

        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andProductIdEqualTo(productId);

        int i = cartMapper.updateByExampleSelective(marketCart,marketCartExample);
        return i;
    }
    @Override
    public int updateNumber(MarketCart marketCart, Integer goodsId) {

        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);

        int i = cartMapper.updateByExampleSelective(marketCart,marketCartExample);
        return i;
    }
}